import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'
import { deepClone, array2tree } from '@/utils'

/**
 * Format backend menu data
 * @param routes
 * @param data
 */
export function generateSidebar(routes, data) {
  data.forEach(item => {
    if (item.is_menu === 1) {
      const menu = {
        path: '/' + item.name,
        component: item.parent_id === null || item.parent_id === 0 ? Layout : resolve => require([`@/views/${item.name}`], resolve), // () => import(`@/views/${item.name}`)
        hidden: !item.is_menu,
        redirect: item.redirect,
        children: [],
        name: 'menu_' + item.id,
        meta: {
          title: item.display_name,
          icon: item.icon
        }
      }

      if (item.children) {
        generateSidebar(menu.children, item.children)
      }
      routes.push(menu)
    }
  })
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, permissions) {
    return new Promise(resolve => {
      const loadMenuData = []
      const permissionData = array2tree(deepClone(permissions))
      Object.assign(loadMenuData, permissionData)
      const accessedRoutes = Object.assign([], asyncRoutes)
      generateSidebar(accessedRoutes, loadMenuData)

      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },

  setPermissions({ commit }, permissions) {
    const loadMenuData = []
    const permissionData = array2tree(deepClone(permissions))
    Object.assign(loadMenuData, permissionData)
    const accessedRoutes = Object.assign([], asyncRoutes)
    generateSidebar(accessedRoutes, loadMenuData)
    // 存储路由
    commit('SET_ROUTES', accessedRoutes)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
